import React, { InputHTMLAttributes, ReactElement } from 'react';
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import classNames from 'classnames';
import { Icon } from '../icon';
import './style.less';

// 用 Omit 剔除 size属性然后继承
// @ts-ignore
export interface InputProps extends InputHTMLAttributes<HTMLElement> {
  /**
   * disabled
   */
  disabled?: boolean;
  /**
   * size
   */
  size?: 'df' | 'lg' | 'sm';
  /**
   * icon
   */
  icon?: IconProp;
  /**
   * prepend
   */
  prepend?: string | ReactElement;
  /**
   * append
   */
  append?: string | ReactElement;

  /**
   * the placeholder
   */
  placeholder?: string;

  /**
   * selected options for select component
   */
  children?: string[];
  /**
   * one option was clicked
   */
  onOptionClick?: (option: string) => void;
  /**
   * icon was clicked
   */
  onIconClick?: () => void;
  /**
   * style
   */
  style?: Object;
}

/**
 * .viking-input-wrapper .is-disabled .input-size-lg/.input-size-sm
 * .input-group .input-group-append .input-group-prepend .input-inner
 */
export const Input: React.FC<InputProps> = props => {
  const {
    disabled,
    size,
    icon,
    prepend,
    append,
    style,
    placeholder,
    children,
    onOptionClick,
    onIconClick,
    ...restProps
  } = props;

  const classes = classNames('viking-input-wrapper', {
    'is-disabled': disabled,
    [`input-size-${size}`]: size,
    'input-group': prepend || append,
    'input-group-append': append,
    'input-group-prepend': prepend,
  });

  const onInput = (e: any) => {
    if (props.type === 'number' && props.maxLength) {
      e.target.value = String(e.target.value).substr(0, props.maxLength);
    }
  };

  return (
    <div className={classes} style={style}>
      {prepend && <div className="viking-input-group-prepend">{prepend}</div>}
      {icon && (
        <div className="icon-wrapper" onClick={onIconClick}>
          <Icon icon={icon} />
        </div>
      )}
      <input
        onInput={onInput}
        placeholder={placeholder}
        className="viking-input-inner"
        disabled={disabled}
        {...restProps}
      />
      <div className="input-selected-options">
        {React.Children.map(children, (option: any) => {
          return (
            <span
              className="input-selected-option"
              onClick={() => onOptionClick && onOptionClick(option)}
            >
              {option}
              <Icon icon="times" />
            </span>
          );
        })}
      </div>
      {append && <div className="viking-input-group-append">{append}</div>}
    </div>
  );
};
Input.displayName = 'input';
